<?php

function p() {
    $argc = func_get_args();
    foreach ($argc as $val) {
        echo '<pre>';
        if (is_bool($val)) {
            var_dump($val);
        } else {
            print_r($val);
        }
    }
    exit;
}

function pp() {
    $argc = func_get_args();
    foreach ($argc as $val) {
        echo '<pre>';
        if (is_bool($val)) {
            var_dump($val);
        } else {
            print_r($val);
        }
    }
}

if (!function_exists('env')) {
    /**
     * 获取环境变量值
     * @access public
     * @param string $name 环境变量名（支持二级 .号分割）
     * @param string $default 默认值
     * @return mixed
     * @throws Exception
     */
    function env($name = null, $default = null)
    {
        return \core\Env::get($name, $default);
    }
}

function debugLog($msg, $logFile = 'debug') {
    \core\lib\Log::log($msg, $logFile);
}

if (!function_exists('redis')) {
    /**
     * @param int $select_db
     * @return \core\lib\Redis
     */
    function redis(int $select_db = 0)
    {
        return \core\lib\Redis::conn($select_db);
    }
}

function format_return($code=200, $data=[], $msg='') {
    $data = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    echo json_encode($data);
}

function return_success($data, $msg='ok', $code=200) {
    $data = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    echo json_encode($data);
    exit;
}

function return_faith($code, $msg, $data=[]) {
    $data = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    echo json_encode($data);
}

/**
 * 获取用户真实IP地址
 * @param int $type
 * @param bool $adv
 * @return mixed
 */
function get_client_ip($type = 0, $adv = true)
{
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}